<template>
  <div class="cart">
    <van-sticky>
      <nav-bar
        style="background: var(--theme-color); color: white"
        :is-back="isBack"
      >
        <template #center>购物车</template>
        <template #right>
          <span style="font-size: 12px" @click="isDelete = !isDelete">
            {{ isDelete ? '删除' : '编辑' }}
          </span>
        </template>
      </nav-bar>
    </van-sticky>
    <div style="height: 80px; background: var(--theme-color)"></div>
    <div class="cart-body">
      <cart-list
        @decrement="decrement"
        @increment="increment"
        :carts="carts"
        v-model="ids"
        ref="cartList"
      />
    </div>
    <van-submit-bar
      button-text="提交订单"
      :price="totalPrice"
      :label="isDelete ? ' ' : '合计：'"
      :style="{ '--inline-block': isDelete ? 'none' : 'inline-block' }"
      v-if="carts.length > 0"
    >
      <template #default>
        <div style="height: 100%; display: flex; algin-items: center">
          <van-checkbox
            checked-color="var(--theme-color)"
            icon-size="16px"
            v-model="isCheckedAll"
            @click="handelCheckedAll"
          >
            {{ isCheckedAll ? '取消全选' : '全选' }}
          </van-checkbox>
        </div>
      </template>
      <template #button>
        <!-- 去结算 -->
        <template v-if="!isDelete">
          <van-button
            round
            color="linear-gradient(#ff9300, #ff5200)"
            size="mini"
            style="padding: 0 10px"
            :disabled="ids.length <= 0"
            @click="handleLinkOrderDetail"
          >
            去结算
            <van-badge color="#ffe7d9">
              <template #content>
                <span style="color: red">{{ ids.length }}</span>
              </template>
            </van-badge>
          </van-button>
        </template>
        <!-- 删除 -->
        <template v-else>
          <van-button
            round
            color="red"
            size="mini"
            style="padding: 0 10px"
            :disabled="ids.length <= 0"
            @click="deleteCart(ids)"
          >
            删除
            <van-badge color="#ffe7d9">
              <template #content>
                <span style="color: red">{{ ids.length }}</span>
              </template>
            </van-badge>
          </van-button>
        </template>
      </template>
    </van-submit-bar>
  </div>
</template>

<script>
import { mapState } from 'vuex'
import { Dialog } from 'vant'
import { queryCats, queryGoodsDetail, editCart, deleteCart } from '@/api'
import NavBar from '@/components/nav-bar/nav-bar.vue'
import CartList from './cpn/cart-list/cart-list.vue'
export default {
  components: {
    NavBar,
    CartList
  },
  data: () => ({
    carts: [],
    ids: [],
    isCheckedAll: false, // 控制子组件选中
    isDelete: false, // 是否删除
    backNameList: ['detail', 'order-detail'], // 支持返回的列表
    isBack: false
  }),
  computed: {
    ...mapState({
      uid: (state) => state.userInfo.id
    }),
    // 计算总价
    totalPrice() {
      return (
        this.carts
          .filter((el) => this.ids.indexOf(el.id) != -1)
          .reduce((pre, el) => pre + el.num * el.goods.price, 0) * 100
      )
    }
  },
  mounted() {
    this.queryCats()
  },
  // 在渲染该组件的对应路由被 confirm 前调用
  // 不！能！获取组件实例 `this`
  // 因为当守卫执行前，组件实例还没被创建
  beforeRouteEnter(to, from, next) {
    next((vm) => {
      // vm 是组件的实例
      vm.isBack = vm.backNameList.indexOf(from.name) != -1
    })
  },
  methods: {
    // 全选和反选(调用子组件的toggleAll方法实现)
    handelCheckedAll() {
      const { cartList } = this.$refs
      cartList.toggleAll(this.isCheckedAll)
    },
    // 查询购物车记录
    async queryCats() {
      this.carts = await queryCats(this.uid)
      this.carts.forEach(async (el, index) => {
        const data = await queryGoodsDetail(el.goods.iid)
        el.shopName = data.shopInfo.name
        this.$set(this.carts, index, el)
      })
    },
    // 减少数量
    async decrement(id) {
      const item = this.carts.find((el) => el.id == id)
      if (item.num > 1) {
        item.num--
        await editCart(id, item.num)
        return
      }
      try {
        // 弹出提示
        await Dialog.confirm({
          title: '提示',
          message: '是否删除'
        })
        this.deleteCart([id])
      } catch (error) {
        console.log(error)
      }
    },
    // 增加数量
    async increment(id) {
      const item = this.carts.find((el) => el.id == id)
      item.num++
      await editCart(id, item.num)
    },
    // 删除购物车
    async deleteCart(id) {
      await deleteCart({ id })
      this.queryCats()
    },
    // 跳转订单详情页
    handleLinkOrderDetail() {
      const info = this.carts
        .map((el) =>
          this.ids.indexOf(el.id) != -1 ? { gid: el.gid, num: el.num } : false
        )
        .filter((el) => el)

      this.$router.push({
        path: '/order-detail',
        query: {
          info: JSON.stringify(info),
          cIds: JSON.stringify(this.ids)
        }
      })
    }
  },
  watch: {
    // 根据ids的长度验证是否全选
    ids(value) {
      this.isCheckedAll =
        value.length === this.carts.length && this.carts.length != 0
    }
  }
}
</script>

<style scoped lang="less">
.cart {
  min-height: calc(100vh - 44px - 10px);
}
.cart-body {
  margin-top: -50px;
  padding: 0 15px;
  box-sizing: border-box;
}

.van-submit-bar {
  bottom: 50px;
  .van-submit-bar__price {
    display: var(--inline-block);
  }
}
</style>
